package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.util.SMSUtils;
import com.itheima.reggie.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: qingtao
 * @Date 2022/3/17 8:55
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired(required = false)
    private UserService userService;

    @Autowired(required = false)
    private HttpSession session;

    //注入redisTemplate
    @Autowired(required = false)
    private RedisTemplate redisTemplate;

    /**
     * 生成验证码
     * @param user
     * @return
     */
    @RequestMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user){
        //1. 获取手机号
        String phone = user.getPhone();

        //2. 生成四位验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();

        //3. 调用阿里的工具类去发送短信(备注： 每位同学发两次就要注释了)
        //SMSUtils.sendMessage("黑马旅游网","SMS_205126318",phone,code);
        System.out.println("本次验证码："+code);
        log.info("=======本次验证码：========="+ code);
        //4. 把验证码存储到session中。
//        session.setAttribute(phone,code); 不好控制有效时间
        //将验证码存储到缓存中,并设置过期时间5分钟
        redisTemplate.opsForValue().set(phone,code,300, TimeUnit.SECONDS);
        //5. 返回信息
        return R.success("发送成功");
    }

    @RequestMapping("/login")
    public R<User> login(@RequestBody Map<String,String> param){
        String phone = param.get("phone");
        String code = param.get("code");
        //从缓存里面获取验证码
        //String codeInSession = (String) session.getAttribute(phone);
        String codeInRedis = (String) redisTemplate.opsForValue().get(phone);
        User user = userService.login(phone, code, codeInRedis);
        if (user!=null){
            session.setAttribute("user",user.getId());
            //将缓存中的验证码删除
            redisTemplate.delete(phone);
        }else {
            return R.error("登录失败");
        }
        return R.success(user);
    }

    /**
     * 退出
     *
     * @return
     */
    @RequestMapping("/loginout")
    public R<String> logout() {
        session.invalidate(); //清除会话
        return R.success("退出成功");
    }

}
